package com.longer.demo.framework.interceptor;

import com.longer.demo.biz.domain.*;
import com.longer.demo.framework.privilege.UserSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: demo
 * @description: 拦截器
 * @author: SunBiaoLong
 * @create: 2019-01-07 17:13
 **/

public class SecurityInterceptor implements HandlerInterceptor {
	private static final String URL_LOGIN = "login";
	private Logger logger = Logger.getLogger(SecurityInterceptor.class);

	@Autowired
	private UserSession userSession;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		setResponse(request,response);
		logger.info(request.getRequestURI());
		if (request.getRequestURL().toString().contains(URL_LOGIN)){
			return true;
		}else {

//			if (!handlePrivilege(request,response)) {
//				return false;
//			}
		}
		return true;
	}

	/**
	 * 设置reponse
	 * @param response
	 */
	private void setResponse(HttpServletRequest request,HttpServletResponse response){
		// 跨域
		//注意：当Access-Control-Allow-Credentials设置为ture时，Access-Control-Allow-Origin不能设置为*
		response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Methods", "GET,POST, PUT, DELETE");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");
	}


	private boolean handlePrivilege(HttpServletRequest request, HttpServletResponse response){
		HttpSession session = request.getSession(false);
		if (session == null) {
			return false;
		}
		UserDO user = userSession.getUser(session);
		//用户未登录
		if (user==null){
			try {
				response.getWriter().println();
			} catch (IOException e) {
				logger.error(e.getMessage(),e);
			}
		}else {

		}

		return true;
	}


	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}
}
